package com.ybw.redis.distributed.lock.controller;

import com.ybw.redis.distributed.lock.service.DistributedLockerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author ybwei
 * @date 2022/2/18 11:46
 **/
@RestController
@RequestMapping("/redis")
@Slf4j
public class RedisController {

    @Resource
    private DistributedLockerService distributedLockerService;

    private int num = 20;

    /**
     * 测试redis分布式锁(没有锁)
     *
     * @return void
     * @throws
     * @methodName: testUnLock
     * @author ybwei
     * @date 2022/2/18 11:46
     */
    @GetMapping("/testUnLock")
    public void testUnLock() throws InterruptedException {
        String s = Thread.currentThread().getName();
        if (num > 0) {
            log.info(s + "排号成功，号码是：" + num);
            num--;
        } else {
            log.info(s + "排号失败,号码已经被抢光");
        }
    }

    /**
     * 测试redis分布式锁(有锁)
     *
     * @return void
     * @throws
     * @methodName: testLock
     * @author ybwei
     * @date 2022/2/18 11:46
     */
    @GetMapping("/testLock")
    public void testLock() throws InterruptedException {
        String lockKey = "lock";
        if (num > 0 && distributedLockerService.tryLock(lockKey, TimeUnit.SECONDS, 10, 20)) {
            log.info("排号成功，号码是：" + num);
            num--;
            // //tryLock测试
            // TimeUnit.SECONDS.sleep(2);
            distributedLockerService.unlock(lockKey);
        } else {
            log.info("排号失败,号码已经被抢光");
        }

    }


    /**
     * 生成分布式锁接口
     *
     * @param lockKey   锁的key
     * @param unit      时间单位
     * @param waitTime  等待时间
     * @param leaseTime 锁的过期时间
     * @return boolean
     * @throws
     * @methodName: tryLock
     */
    @GetMapping("/tryLock")
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) throws InterruptedException {
        return distributedLockerService.tryLock(lockKey, unit, waitTime, leaseTime);
    }

}